import socket
from datetime import date
import tkinter
from tkinter import filedialog
import tkinter.messagebox as messagebox
from icon import img
import base64,os
# import ctypes

# 构建基础窗口
def Window():
    global window, entry_text
    # 窗口信息
    window = tkinter.Tk()
    # window.overrideredirect(True)
    # ctypes.windll.shcore.SetProcessDpiAwareness(1) #调用api设置成由应用程序缩放
    # ScaleFactor = ctypes.windll.shcore.GetScaleFactorForDevice(0)  #调用api获得当前的缩放因子
    # window.tk.call('tk', 'scaling', ScaleFactor/70) #设置缩放因子
    window.resizable(False, False)  # 横纵均不允许调整
    window.title('日志保存路径')
    tmp = open("tmp.ico", "wb+")
    tmp.write(base64.b64decode(img))
    tmp.close()
    window.iconbitmap('tmp.ico')
    os.remove("tmp.ico")
    window.attributes('-topmost',-1)
    window.protocol("WM_DELETE_WINDOW", Callback)

    # 居中显示
    screenwidth = window.winfo_screenwidth()  # 获取显示屏宽度
    screenheight = window.winfo_screenheight()  # 获取显示屏高度
    width = 500
    height = 100
    size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)  # 设置窗口居中参数
    window.geometry(size)  # 让窗口居中显示

    # 标签组件
    label = tkinter.Label(window, text='存储路径：', font=('微软雅黑', 12))
    label.place(x=10, y=34.5)

    # 输入框控件
    entry_text = tkinter.StringVar()
    entry = tkinter.Entry(window, textvariable=entry_text, font=('微软雅黑', 10), width=42, state='readonly')
    entry.place(x=90, y=38)
    # 按钮组件
    button = tkinter.Button(window, text='选择', command=get_path,font=('微软雅黑',12))
    button.place(x=445, y=31)

    # 常驻窗口
    window.mainloop()

# 按钮控件获取保存目录
def get_path():
    global a
    a = []
    # 返回一个字符串，且只能获取文件夹路径，不能获取文件的路径。
    path = filedialog.askdirectory(title='请选择一个目录')
    a.append(path)
    entry_text.set(path)
    if len(entry_text.get()) == 0:
        messagebox.showwarning('提示', '未选择路径，请先选择！')
    else:
        messagebox.showwarning('提示', '将自动命名保存，请关闭窗口！')
    return path

# 判断退出的条件，需要强制要求选择路径。
def Callback():
    if len(entry_text.get()) == 0:
        messagebox.showwarning('提示', '请选择路径后再关闭！')
    else:
        window.destroy()

def syslog_monitor_savepath(user_path):
    print("SYSLOG服务已开启，日志将实时打印并保存！\n")
    udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp.bind(('0.0.0.0', 514))
    while True:
        rec_msg, addr = udp.recvfrom(2048)
        client_ip, client_port = addr
        msg = rec_msg.rstrip(b'\x00').decode('utf-8', 'ignore')
        log = "日志来源IP：" + client_ip + " 日志ID：" + msg[5:]
        print(log)
        filename = user_path + client_ip + '_' + str(date.today()) + ".log"
        with open(filename, 'a+', encoding="utf-8") as f:
            f.write(log + "\n")

def syslog_monitor_print():
    print("SYSLOG服务已开启，日志将实时打印！\n")
    udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp.bind(('0.0.0.0', 514))
    while True:
        rec_msg, addr = udp.recvfrom(2048)
        client_ip, client_port = addr
        msg = rec_msg.rstrip(b'\x00').decode('utf-8', 'ignore')
        log = "日志来源IP：" + client_ip + " 日志ID：" + msg[5:]
        print(log)

if __name__ == "__main__":
    print("欢迎使用SYSLOG服务器")
    print("== == == == == == == == == == == =")
    print("请选择SYSLOG服务器使用模式：  模式1：实时打印显示Log日志; 模式2:实时打印并保存至用户指定路径。")
    print("请输入对应编号数字选择，输入1或者2。")
    print("== == == == == == == == == == == =")
    while True:
        try:
            Num = int(input("请输入模式编号："))
        except ValueError:
            print('您的输入有误,请重新输入!\n')
        else:
            if Num == 1:
                syslog_monitor_print()
            elif Num == 2:
                Window()
                user_path = str(a[0] + "//")
                syslog_monitor_savepath(user_path)
            else:
                print('您输入的模式不存在！\n')
